package com.web.gatewayservice.filter;

import com.web.util.JwtUtils;
import com.web.util.RsaUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * Token验证授权的全局过滤器
 */
@Component
public class TokenAuthorizationFilter implements GlobalFilter, Ordered {

    //白名单
    private static final String[] WHITE_LIST = {"/login","/register"};

    private static Logger logger = LoggerFactory.getLogger(TokenAuthorizationFilter.class);

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //获得请求和响应对象
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        //白名单包含的url直接放行
        for(String url : WHITE_LIST){
            if(request.getURI().toString().contains(url)){
                return chain.filter(exchange);
            }
        }
        //获得请求头中的token信息
        String token = request.getHeaders().getFirst("Authorization");
        logger.info("获得token：{}",token);
        //判断token是否为空
        if(StringUtils.hasText(token)){
            try {
                //对token进行解析
                String username = JwtUtils.getUsernameFromToken(token, RsaUtils.publicKey);
                logger.info("解析token成功：{}", username);
                //放行请求
                return chain.filter(exchange);
            }catch (Exception ex){
                logger.error("解析token失败：{}",ex.getMessage());
                //返回客户端错误信息
                response.setStatusCode(HttpStatus.OK);
                DataBuffer wrap = response.bufferFactory().wrap("Token is wrong!".getBytes());
                return response.writeWith(Mono.just(wrap));
            }
        }
        logger.error("token为空");
        //返回客户端错误信息
        response.setStatusCode(HttpStatus.OK);
        DataBuffer wrap = response.bufferFactory().wrap("Token is empty!".getBytes());
        return response.writeWith(Mono.just(wrap));
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
